/**
 * Created by Dell on 2017/5/22.
 */
'use strict';
const pg = require('../lib/pgClient');
const log = require('../models/basicinfo');
/**
 * 后台编辑基本信息
 * @param params
 * @param args
 * @param callback
 */
exports.upd_basic = function(params, args, callback){
    const sql1 = 'SELECT id FROM basicinfo';//查看是否已经有基本信息
    const sql2 = 'INSERT INTO basicinfo (app,thirdpartyapp) VALUES ( $1, $2)';//添加基本信息
    let sql3 = 'UPDATE basicinfo SET';//修改基本信息
    let number = 1;
    let params2 = [];
    if(args.app && !args.third){
        sql3 += ' app = $'+number;
        number++;
        params2 = [
            args.app,
            ''
        ]
    }else if(args.third && !args.app ){
        sql3 += ' thirdpartyapp = $'+number;
        number++;
        params2 = [
            '',
            args.third
        ]
    }else {
        sql3 += ' app = $'+number+' , thirdpartyapp = $'+(number+1);
        number++;
        params2 = [
            args.app,
            args.third
        ]
    }
    pg.query(sql1,[], function(err,rusult){//查找是否已经存在基本信息
        if(err){
            callback (err, null);//报错
        }else if(rusult.rowCount==0){
            pg.query(sql2,params2,function(err,result){//不存在基本信息，添加基本信息
                if(err){
                    callback (err, null);//报错
                }else {
                    callback(err, result);//返回数据
                }
            })
        }else{
            pg.query(sql3,params,function(err,result){//已经存在基本信息，修改基本信息
                if(err){
                    callback (err, null);//报错
                }else{
                    callback (err, result);//返回数据
                }
            })
        }
    })
};
/**
 * 查看基本信息
 * @param callback
 */
const list_sql = 'SELECT app, thirdpartyapp FROM basicinfo ';//查看基本信息（基本信息就一条）
exports.list = function(callback){
    pg.query(list_sql, [], function(err, result){//执行查找操作
        if(err){
            callback (err, null);//报错
        }else if(result.rowCount == 0){
            callback (err, 'null');//没有基本信息
        }else{
            callback (err, result);//返回有效信息
        }
    })
};